package com.fenghongzhang.day013;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.LruCache;

import androidx.annotation.NonNull;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ImageUtil {

    private static ImageUtil imageUtil;

    private static final String TAG = "ImageUtil";
    //3级内存
    LruCache<String, Bitmap> cache;

    private String path;
    ExecutorService executorService;
    private ImageUtil(){
        executorService = Executors.newSingleThreadExecutor();
        int l = (int) (Runtime.getRuntime().maxMemory() / 10);
        //init
        cache = new LruCache<String,Bitmap>(l){
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getByteCount();
            }
        };
    }

    public static ImageUtil getInstance(){
        if(imageUtil == null){
            synchronized (ImageUtil.class){
                if(imageUtil == null){
                    imageUtil = new ImageUtil();
                }
            }
        }
        return imageUtil;
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            Bitmap bitmap = (Bitmap) msg.obj;
            myListener.click(bitmap);

        }
    };

    public void loading(final String url){

        //http://www.qubaobei.com/ios/cf/uploadfile/132/3/2127.jpg
        final String name = url.substring(url.lastIndexOf("/")+1,url.lastIndexOf("."));

        //1,先内存里面读取
        final Bitmap bitmap = cache.get(name);
        if(bitmap !=null){
            //
            Log.i(TAG, "loading: 从内存读取");
            //如果内存有,就读取
            myListener.click(bitmap);
        }else{
            //2,sd卡里读取
                Bitmap bitmap1 = BitmapFactory.decodeFile(new File(Environment.getExternalStorageDirectory() + File.separator + "image" + File.separator, name + ".jpg").getAbsolutePath());
                if(bitmap1 != null){
                    Log.i(TAG, "loading: 从sd卡读取");
                    myListener.click(bitmap1);
                    //放入到内存一份
                    cache.put(name,bitmap1);
                }else{
                    //3,从网络上读取
                    executorService.execute(new Runnable() {
                        @Override
                        public void run() {
                            //从网络下载
                            Log.i(TAG, "run: 从网络中读取");
                            try {
                                URL url1 = new URL(url);
                                HttpURLConnection urlConnection =(HttpURLConnection) url1.openConnection();

                                if(urlConnection.getResponseCode() == 200){
                                    InputStream inputStream = urlConnection.getInputStream();
                                    //
                                    Bitmap bitmap1 = BitmapFactory.decodeStream(inputStream);

                                    //1,存sd
//                                Environment.getExternalStorageState()
                                    saveToSd(bitmap1, name);

                                    //2,存到内存
                                    cache.put(name,bitmap1);

                                    //发送
                                    Message obtain = Message.obtain();
                                    obtain.obj = bitmap1;
                                    handler.sendMessage(obtain);
                                }

                            } catch (MalformedURLException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });

                }
        }
    }

    /**
     * 保存到sd
     * @param bitmap1
     * @param name
     * @throws FileNotFoundException
     */
    private void saveToSd(Bitmap bitmap1, String name) throws FileNotFoundException {
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            ///storage/emulated/0/image/
            File file = new File(Environment.getExternalStorageDirectory() + File.separator + "image" + File.separator);
            ///storage/emulated/0/image/2127.jgp
            if(!file.exists()){
                file.mkdirs();
            }
            File file1 = new File(file, name+".jpg");
            path = file1.getAbsolutePath();
            Log.i(TAG, "saveToSd: "+path);
            FileOutputStream fileOutputStream = new FileOutputStream(file1);
            bitmap1.compress(Bitmap.CompressFormat.JPEG,100,fileOutputStream);
        }
    }

    public interface MyListener{
        void click(Bitmap bitmap);
    }

    private MyListener myListener;

    public void setMyListener(MyListener myListener) {
        this.myListener = myListener;
    }
}
